<template>
  <div class="job-progress">
    <div ref="chartRef" class="chart-container"></div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onUnmounted } from 'vue'
  import * as echarts from 'echarts'

  const chartRef = ref<HTMLElement | null>(null)
  let chart: echarts.ECharts | null = null
  //当前视口宽度
  let nowClientWidth = ref(document.documentElement.clientWidth)
  //换算方法
  function nowSize(val: number, initWidth = 1920) {
    return val * (nowClientWidth.value / initWidth)
  }

  // 模拟数据
  const mockData = {
    total: 100,
    completed: 75,
    inProgress: 15,
    pending: 10,
  }

  const initChart = () => {
    if (!chartRef.value) return

    chart = echarts.init(chartRef.value)

    const option = {
      title: {
        text: '作业进度概览',
        left: 'center',
        textStyle: {
          fontSize: nowSize(16),
          fontWeight: 'bold',
        },
      },
      tooltip: {
        trigger: 'item',
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        textStyle: {
          fontSize: nowSize(14),
        },
      },
      series: [
        {
          name: '作业进度',
          type: 'pie',
          radius: '50%',
          data: [
            { value: mockData.completed, name: '已完成' },
            { value: mockData.inProgress, name: '进行中' },
            { value: mockData.pending, name: '待处理' },
          ],
          label: {
            fontSize: nowSize(14),
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
        },
      ],
    }

    chart.setOption(option)
  }

  onMounted(() => {
    initChart()
    window.addEventListener('resize', handleResize)
  })

  onUnmounted(() => {
    if (chart) {
      chart.dispose()
    }
    window.removeEventListener('resize', handleResize)
  })

  const handleResize = () => {
    if (chart) {
      nowClientWidth.value = document.documentElement.clientWidth
      chart.setOption({
        title: {
          textStyle: {
            fontSize: nowSize(16),
          },
        },
        legend: {
          textStyle: {
            fontSize: nowSize(14),
          },
        },
        series: [
          {
            label: {
              fontSize: nowSize(14),
            },
          },
        ],
      })
      chart.resize()
    }
  }
</script>

<style scoped>
  .job-progress {
    width: 100%;
    height: 100%;
  }

  .chart-container {
    width: 100%;
    height: 300px;
  }
</style>
